/*
 * hex_body_visualizer.c
 * This file is part of gURL
 *
 * Copyright (C) 2014 - Aleksey Konovalov
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Library General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "hex_body_visualizer.h"

#ifdef HAVE_GHEX

#include "body_visualizer.h"
#include <gtkhex.h>

struct _HexBodyVisualizer {
    GtkBox parent;
    GtkWidget* hex; 
    HexDocument* hex_doc;
    size_t doc_length;
};

struct _HexBodyVisualizerClass {
    GtkBoxClass parent;
};

static void hex_body_visualizer_interface_init(BodyVisualizerInterface* iface);

G_DEFINE_TYPE_WITH_CODE(HexBodyVisualizer, hex_body_visualizer, GTK_TYPE_BOX,
                        G_IMPLEMENT_INTERFACE(BODY_VISUALIZER_TYPE,
                                              hex_body_visualizer_interface_init))

static void hex_body_visualizer_change_session(BodyVisualizer* self,
                                                Session* session) {
    HexBodyVisualizer* hbv = HEX_BODY_VISUALIZER(self);
    hex_document_delete_data(HEX_DOCUMENT(hbv->hex_doc), 0, hbv->doc_length, FALSE);
    hbv->doc_length = 0;
    if(session) {
        const GString* body = session_get_response_body(session);
        hex_document_set_data(HEX_DOCUMENT(hbv->hex_doc), 0, body->len, 0,
                              (guchar*)body->str, FALSE);
        hbv->doc_length = body->len;
    }
}

static void hex_body_visualizer_interface_init(BodyVisualizerInterface* iface) {
    iface->change_session = hex_body_visualizer_change_session;
    iface->name = "HEX";
}

static void hex_body_visualizer_init(HexBodyVisualizer* self) {
    self->hex_doc = hex_document_new();
    self->hex = gtk_hex_new(self->hex_doc);
    g_object_set(G_OBJECT(self->hex), "margin", 0, NULL);
    gtk_widget_set_hexpand(self->hex, TRUE);
    gtk_hex_set_geometry(GTK_HEX(self->hex), 32, 1);
    gtk_container_add(GTK_CONTAINER(self), self->hex);
    gtk_widget_show(self->hex);
    self->doc_length = 0;
    self->hex_doc->views = g_list_append(self->hex_doc->views, self->hex);
    gtk_widget_set_has_window(GTK_WIDGET(self->hex), TRUE);
}

static void hex_body_visualizer_class_init(HexBodyVisualizerClass* klass) {}

GtkWidget* hex_body_visualizer_new() {
    return g_object_new(HEX_BODY_VISUALIZER_TYPE, NULL);
}

#endif /* HAVE_GHEX */
